package com.jd.finance.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jd.finance.core.mapper.GrantMapper;
import com.jd.finance.core.mapper.NodeMapper;
import com.jd.finance.core.mapper.RoleMapper;
import com.jd.finance.core.pojo.entity.Grantt;
import com.jd.finance.core.pojo.entity.Node;
import com.jd.finance.core.pojo.entity.Role;
import com.jd.finance.core.service.GrantService;
import com.jd.finance.core.service.OpreateLogService;
import com.jd.finance.result.BaseResult;
import com.jd.finance.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 角色权限中间表 服务实现类
 * </p>
 *
 * @author LiQingBo
 * @since 2022-05-20
 */
@Service
public class GrantServiceImpl extends ServiceImpl<GrantMapper, Grantt> implements GrantService {

    @Resource
    private GrantMapper grantMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private NodeMapper nodeMapper;

    @Autowired
    private OpreateLogService opreateLogService;

    /**
     * 添加角色-节点中间表
     * @param uid
     * @param listId
     * @param roleId
     * @param request
     * @return
     */
    @Override
    public BaseResult addNodeRole(Integer uid, Integer listId, Integer roleId, HttpServletRequest request) {
        if(uid == null){
            log.error("管理员id为空");
            return BaseResult.error().message("管理员id为空");
        }
        if(listId == null){
            log.error("节点id为空");
            return BaseResult.error().message("节点id为空");
        }
        if(roleId == null){
            log.error("角色id为空");
            return BaseResult.error().message("角色id为空");
        }
        //判断传过来的id数据库里是否一样
        QueryWrapper<Role> qw1 = new QueryWrapper<>();
        qw1.eq("role_id",roleId);
        Role role = roleMapper.selectOne(qw1);
        if (role == null){
            log.error("角色id不存在");
            return BaseResult.error().message("角色id不存在");
        }

        QueryWrapper<Node> qw = new QueryWrapper<>();
        qw.eq("list_id",listId);
        Node node = nodeMapper.selectOne(qw);
        if (node == null){
            log.error("节点id不存在");
            return BaseResult.error().message("节点id不存在");
        }

        Grantt grantt = new Grantt();
        grantt.setListId(listId);
        grantt.setRoleId(roleId);
        int i = grantMapper.insert(grantt);
        if (i == 0){
            log.error("添加失败");
            return BaseResult.error().message("添加失败");
        }

        //添加操作日志
        boolean add = opreateLogService.add(uid, "添加", "添加角色-节点中间表", IpUtil.getIpAddr(request));
        if (!add){
            log.error("操作日志添加失败");
            return BaseResult.error().message("操作日志添加失败");
        }
        return BaseResult.ok().data("tianjiajieguo:",i);
    }
}
